import { getOrderPage, handleEvent } from '@/services/center';
import { findByCodeList } from '@/services/login';
import { formatNumber, getOptions, jumpUrl } from '@/utils';
import { useRequest } from 'ahooks';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Divider,
  Flex,
  Form,
  Row,
  Select,
  Space,
  Typography,
} from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { useIntl } from 'umi';

import { typeColor } from '@/utils/common';
import ApplyDetail from './ApplyDetail';
import ApplyModal from './ApplyModal';

//  我的贷款申请
const Apply: React.FC = () => {
  const intlPageParams = {
    page: 1,
    pageSize: 9999,
  };
  const [pagePamras, setPagePamras] = useState(intlPageParams);

  const intl = useIntl();
  const [visible, setVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [record, setRecord] = useState<Center.Record>();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<Center.Record[]>([]);
  const { data: optionsList } = useRequest(() =>
    findByCodeList({ code: 'productType,orderListStatus' }),
  );
  // const onChange: PaginationProps['onChange'] = (page) => {
  //   setPagePamras({
  //     ...pagePamras,
  //     page,
  //   });
  //   document.documentElement.scrollTop = 0;
  // };

  const statusList = (value: string) => {
    switch (value) {
      case '1':
        return {
          color: '#FF8F00',
        };
      case '2':
      case '4':
        return {
          color: '#43B649',
        };
      case '3':
      case '5':
      case '7':
        return {
          color: '#FA5F30',
        };
      case '6':
        return {
          color: '#0270DF',
        };
    }
  };

  const [form] = Form.useForm();
  const values = Form.useWatch([], form);

  const { orderListStatus, productType } = optionsList?.data || {};
  const loadMoreData = async () => {
    const { time, status } = form.getFieldsValue();
    const { pageSize, page } = pagePamras;
    const [first, seconrd] = time || [];

    try {
      setLoading(true);
      const { data: applyList } = await getOrderPage({
        p: page,
        s: pageSize,
        status,
        ...(first ? { startTime: dayjs(first).valueOf() } : {}),
        ...(seconrd ? { endTime: dayjs(seconrd).valueOf() } : {}),
      });
      const { records } = applyList;

      setData(records);
      setLoading(false);
    } catch {
      setLoading(false);
    }
  };
  useEffect(() => {
    loadMoreData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pagePamras]);
  useEffect(() => {
    handleEvent('Personal_Center_loan_application_access');
  }, []);
  return (
    <div className="apply">
      <Form
        form={form}
        onFinish={() => {
          setPagePamras(intlPageParams);
        }}
      >
        <Flex align="baseline" justify="space-between" style={{ paddingTop: 24 }}>
          <Flex gap={24} align="center">
            <Form.Item name="time">
              <DatePicker.RangePicker style={{ background: 'none' }} size="large" />
            </Form.Item>
            <Form.Item name="status">
              <Select
                allowClear
                options={getOptions(orderListStatus)}
                size="large"
                className="apply_select"
                placeholder={intl.formatMessage({ id: 'center.choose_status' })}
                style={{ width: 170, borderRadius: 6 }}
                variant="borderless"
              />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button
                  style={{ minWidth: '90px', boxShadow: 'none' }}
                  size="large"
                  type="primary"
                  htmlType="submit"
                >
                  {intl.formatMessage({ id: 'center.search' })}
                </Button>
                <Button
                  style={{ minWidth: '90px', background: 'transparent' }}
                  size="large"
                  onClick={() => {
                    if (values && Object.keys(values).length > 0) {
                      if (
                        Object.values(values).some((item) => {
                          return item;
                        })
                      ) {
                        form.resetFields();
                        setTimeout(() => {
                          setPagePamras(intlPageParams);
                        }, 0);
                      }
                    }
                  }}
                >
                  {intl.formatMessage({ id: 'center.reset' })}
                </Button>
              </Space>
            </Form.Item>
          </Flex>
        </Flex>
      </Form>
      <Card
        bordered={false}
        loading={loading}
        styles={{ body: { padding: '0' } }}
        style={{ minHeight: '50vh', marginTop: 6, background: 'none', boxShadow: 'none' }}
      >
        {data.length > 0 ? (
          <>
            <Row gutter={[24, 24]}>
              {data.map((item) => {
                const {
                  orderNo,
                  createdDate,
                  productType: type,
                  merchantLogo,
                  productName,
                  applyAmount,
                  applyTerm,
                  approvedLoanTerm,
                  loanTerm,
                  orderUserStatus: status,
                  rewardFlag,
                  additionalInformationFlag,
                  id,
                  productId,
                  approvedAmount,
                  loanAmount,
                } = item;
                const typeName = productType?.find((item) => item.value == type)?.name;
                const amount =
                  status == 4 ? approvedAmount : status == 6 ? loanAmount : applyAmount;
                const term = status == 4 ? approvedLoanTerm : status == 6 ? loanTerm : applyTerm;
                const { color } = statusList(status?.toString()) || {};
                const { bgColor, color: typeColors } =
                  typeColor.find((item) => item.key == type) || {};
                const statusName = orderListStatus?.find((item) => item.value == status)?.name;
                return (
                  <Col
                    onClick={() => {
                      setDetailVisible(true);
                      setRecord({ ...item, typeName, statusName });
                    }}
                    style={{ cursor: 'pointer' }}
                    span={8}
                    key={id}
                  >
                    <Card bordered={false} style={{ boxShadow: 'none', height: '100%' }}>
                      <Flex
                        align="center"
                        style={{ color: '#999999', lineHeight: '32px' }}
                        justify="space-between"
                      >
                        <div>
                          {intl.formatMessage({ id: 'center.apply_id' })}：{orderNo}
                        </div>
                        <Space size={6}>
                          {status == 1 ? (
                            <div>
                              <Button
                                onClick={() => {
                                  jumpUrl(`/supplement?id=${productId}&orderId=${id}&order=true`);
                                }}
                                type="text"
                                style={{
                                  background: 'linear-gradient(90deg, #FFB041 0%, #FE9B5A 100%)',
                                  fontWeight: 700,
                                  color: '#fff',
                                  padding: '4px 10px',
                                }}
                              >
                                {intl.formatMessage({
                                  id: additionalInformationFlag
                                    ? 'home.other_data'
                                    : 'center.other_data',
                                })}
                              </Button>
                            </div>
                          ) : null}
                          {rewardFlag ? (
                            <div>
                              <Button
                                type="primary"
                                onClick={(e) => {
                                  setVisible(true);
                                  setRecord(item);
                                  e.stopPropagation();
                                }}
                                style={{
                                  backgroundColor: '#0270DF',
                                  fontWeight: 700,
                                  padding: '4px 10px',
                                }}
                              >
                                {intl.formatMessage({ id: 'center.reward' })}
                              </Button>
                            </div>
                          ) : null}
                        </Space>
                      </Flex>
                      <Divider style={{ margin: '16px 0 12px' }} />

                      <Flex gap={8} justify="space-between" align="center">
                        <div style={{ width: '100%' }}>
                          <Flex
                            style={{
                              color: typeColors,
                              padding: '2px 14px',
                              marginBottom: 12,
                              background: `linear-gradient(90deg, ${bgColor} 0%, rgba(255, 242, 232, 0.1) 100%)`,
                              borderLeft: `2px solid ${typeColors}`,
                            }}
                          >
                            {typeName}
                          </Flex>
                          <Flex align="center" gap={4}>
                            <img src={merchantLogo} height={19} />
                            <Typography.Text
                              ellipsis={{ tooltip: productName }}
                              style={{
                                fontSize: 15,
                                maxWidth: '150px',
                                fontWeight: 'bold',
                                color: '#333',
                                whiteSpace: 'nowrap',
                              }}
                            >
                              {productName}
                            </Typography.Text>

                            <div
                              style={{
                                padding: '0px 10px',
                                color: '#fff',
                                background: color,
                                borderRadius: 3,
                                transform: 'skew(-8deg)',
                                whiteSpace: 'nowrap',
                                fontSize: 13,
                              }}
                            >
                              {statusName}
                            </div>
                          </Flex>
                        </div>
                      </Flex>
                      <Flex justify="space-between" style={{ marginTop: 24 }}>
                        <Space style={{ flexDirection: 'column' }} size={4} align="start">
                          <Col style={{ color: '#999' }}>
                            {intl.formatMessage({
                              id:
                                status == 6
                                  ? 'center.apply_money'
                                  : status == 4
                                  ? 'center.approved_money'
                                  : 'center.apply_amount',
                            })}
                          </Col>
                          <Col style={{ fontSize: 18, fontWeight: 'bold', color: '#333' }}>
                            {formatNumber(amount.toFixed(2), false)}
                          </Col>
                        </Space>
                        <Space style={{ flexDirection: 'column' }} size={4} align="start">
                          <Col style={{ color: '#999' }}>
                            {intl.formatMessage({ id: 'center.apply_date' })}
                          </Col>
                          <Col style={{ fontSize: 18, fontWeight: 'bold', color: '#333' }}>
                            {term}
                          </Col>
                        </Space>
                        <Space style={{ flexDirection: 'column' }} align="start">
                          <Col style={{ color: '#999' }}>
                            {intl.formatMessage({ id: 'center.apply_time' })}
                          </Col>
                          <Col style={{ color: '#999' }}>
                            {dayjs(createdDate).format('YYYY-MM-DD')}
                          </Col>
                        </Space>
                      </Flex>
                    </Card>
                  </Col>
                );
              })}
            </Row>
            {/* <Col style={{ marginTop: '20px', display: 'flex', justifyContent: 'flex-end' }}>
              <Pagination
                current={page}
                pageSize={pageSize}
                onChange={onChange}
                total={total}
                onShowSizeChange={(current: number) => {
                  setPagePamras({
                    ...pagePamras,
                    pageSize: current,
                  });
                }}
                showSizeChanger
                showQuickJumper
              />
            </Col> */}
          </>
        ) : (
          <Flex
            align="center"
            justify="center"
            style={{ height: '100%', color: '#0270DF ', fontSize: 18, paddingTop: '25vh' }}
          >
            {intl.formatMessage({ id: 'center.no_data' })}
          </Flex>
        )}
      </Card>
      <ApplyModal
        handleOk={() => {
          setVisible(false);
          loadMoreData();
        }}
        visible={visible}
        handleCancel={() => {
          setVisible(false);
        }}
        record={record || {}}
      />
      <ApplyDetail
        record={record || {}}
        visible={detailVisible}
        handleCancel={() => {
          setDetailVisible(false);
        }}
      />
    </div>
  );
};

export default Apply;
